//
//  RHDeviceInfoController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/25.
//

#import "RHDeviceInfoController.h"
#import "JXCategoryView.h"
#import "RHDeviceDataController.h"
#import "JXCategoryListContainerView.h"
#import "RHDeviceParaSetVC.h"
#import "RHEndPointTypeModel.h"
#import "DevChartTypeModel.h"
#import "RHEndPointModel.h"
#import "RHNavTitleView.h"
#import "RHDeviceInverterDataVC.h"
#import "RHDataMonitor233VC.h"
#import "RHDataMonitorMe61VC.h"
#import "RHDataMonitorMe215VC.h"
#import "RHDataMonitorMe167MVC.h"

@interface RHDeviceInfoController ()<JXCategoryListContainerViewDelegate,JXCategoryViewDelegate,JXCategoryTitleViewDataSource>

@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, strong) JXCategoryTitleView *categoryView;

@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;


@property (nonatomic, strong) RHDeviceDataController *dataController;


//端点类型数组
@property (nonatomic ,strong) NSMutableArray <RHEndPointTypeModel*>*typeArray;

@property (nonatomic ,strong) LYEmptyView *emptyView;

@property (nonatomic, strong) RHNavTitleView *titleView;

@property (nonatomic ,copy) NSString *currentEndpointName;
@end

@implementation RHDeviceInfoController
-(instancetype)initWithDevModel:(RHDeviceModel*)devModel endpointName:(NSString*)endpointName
{
    if (self = [super init]) {
        _deviceModel = devModel;
        _currentEndpointName = endpointName;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.deviceModel.deviceName;
    [self.view setBackgroundColor:CFTabViewBgColor];
    
    [self setupUI];
    [self getDeviceStatus];
    [self getEndPointReration];
}



- (void)setupUI{
    self.titleView = [[RHNavTitleView alloc]init];
    [self.titleView hideArrowImg];
    self.titleView.devNameLab.text = self.deviceModel.deviceName;
    self.titleView.devIdLab.text = self.deviceModel.deviceId;
    self.titleView.status = self.deviceModel.status;
    self.navigationItem.titleView = self.titleView;
    
    UIButton *setButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 64)];
    [setButton setImage:[UIImage imageNamed:@"device_set_icon"] forState:UIControlStateNormal];
    [setButton setBackgroundColor:UIColor.clearColor];
    [setButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [setButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [setButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [setButton addTarget:self action:@selector(setDvicePara) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:setButton];
//    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self.view addSubview:self.listContainerView];
    
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 50)];
    self.categoryView.titles = self.titles;
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
    self.categoryView.titleSelectedColor = CMainColorGreen;
    self.categoryView.titleColor = kCOLOR_HEX(@"969799");
    self.categoryView.titleFont = [UIFont systemFontOfSize:14];
    self.categoryView.titleSelectedFont = [UIFont boldSystemFontOfSize:14];
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = NO;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.cellWidth = JXCategoryViewAutomaticDimension;
    self.categoryView.cellSpacing = 20;
//    self.categoryView.contentEdgeInsetLeft = 20;
//    self.categoryView.contentEdgeInsetRight = 20;
    self.categoryView.titleLabelVerticalOffset = -10;
    [self.view addSubview:self.categoryView];
    self.categoryView.listContainer = self.listContainerView;
    
    JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
//     backgroundView.size = CGSizeMake(60, 3);
     backgroundView.indicatorColor = CMainColorGreen;
     backgroundView.indicatorHeight = 3;
//     backgroundView.indicatorWidth = 60;
     backgroundView.verticalMargin = -10;
     backgroundView.indicatorCornerRadius = 1.5;

     _categoryView.indicators = @[backgroundView];
    
    
    [_categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(0);
        make.height.mas_equalTo(50);
    }];
    
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(self.categoryView.mas_bottom).offset(0);
        make.bottom.mas_offset(0);
    }];
    
    kWeakSelf;
    [[setButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {

    }];
}

#pragma mark ----- 设置模块参数 --------
-(void)setDvicePara{
    RHDeviceParaSetVC *setVC = [[RHDeviceParaSetVC alloc]init];
    setVC.deviceModel = self.deviceModel;
    [self.navigationController pushViewController:setVC animated:YES];
}


#pragma mark ------ 获取设备状态
-(void)getDeviceStatus
{
//    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@%ld",H_getDeviceInfo,self.deviceModel.device_id];
    [BaseModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.titleView.status = request.responseJSONObject[@"data"][@"status"];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
    }];
}

#pragma mark ----- 更新模块在线状态 -------
//这里只对状态处理,不对整个结构进行重新加载,会比较慢,体验不好
-(void)getModueStatus
{
//    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%@",H_getDevRelationTypeList,self.deviceModel.deviceId];
    [RHEndPointTypeModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSArray *typeArr = resultModel.data;
            UIViewController *vc = self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
            if ([vc isKindOfClass:[RHDeviceDataController class]]) {
                RHDeviceDataController *dataVC = (RHDeviceDataController*)vc;
                if (dataVC && (self.categoryView.selectedIndex < typeArr.count)) {
                    [dataVC updateEndpointTypeModel:typeArr[self.categoryView.selectedIndex]];
                }
            }
            //逆变器
            if ([vc isKindOfClass:[RHDeviceInverterDataVC class]]) {
                RHDeviceInverterDataVC *inverterVC = (RHDeviceInverterDataVC*)vc;
                if (inverterVC && (self.categoryView.selectedIndex < typeArr.count)) {
                    [inverterVC updateEndpointTypeModel:typeArr[self.categoryView.selectedIndex]];
                }
            }
           
            if ([vc isKindOfClass:[RHDataMonitor233VC class]]) {
                RHDataMonitor233VC *monitorVC = (RHDataMonitor233VC*)vc;
                if (monitorVC && (self.categoryView.selectedIndex < typeArr.count)) {
                    [monitorVC updateEndpointTypeModel:typeArr[self.categoryView.selectedIndex]];
                }
            }
        }else{
            [self.view addSubview:self.emptyView];;
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ----- 获取设备节点关系 -------
- (void)getEndPointReration{
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%@",H_getDevRelationTypeList,self.deviceModel.deviceId];
    [RHEndPointTypeModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSArray *typeArr = resultModel.data;
            
            NSMutableArray *mtbArr = [NSMutableArray array];
            [self.typeArray removeAllObjects];
            [typeArr enumerateObjectsUsingBlock:^(RHEndPointTypeModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.display) {
                    [mtbArr addObject:obj.endpointTypeName];
                    [self.typeArray addObject:obj];
                    
                }
               
            }];
            self.typeArray = typeArr.mutableCopy;
            self.titles =mtbArr.copy;
            self.categoryView.titles = self.titles;
            [self.categoryView reloadData];
            
            [self.typeArray enumerateObjectsUsingBlock:^(RHEndPointTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                //如果是从工商储过来
                if ([self.currentEndpointName isEqualToString:obj.endpointTypeName]) {
                    [self.categoryView selectItemAtIndex:idx];
                    *stop = YES;
                    return;
                }
            }];
        }else{
           
            [self.view addSubview:self.emptyView];
 
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}


#pragma mark - JXCategoryViewDelegate

// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    // 侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    
//    self.subTitleLab.text = index==0?self.deviceModel.deviceId:self.deviceModel.typeName;
}

// 滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

#pragma mark - JXCategoryListContainerViewDelegate
// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return  self.titles.count;
}

// 返回各个列表菜单下的实例，该实例需要遵守并实现 <JXCategoryListContentViewDelegate> 协议
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    kWeakSelf;
    RHEndPointTypeModel *typeModel = self.typeArray[index];
   
    //233k
    if ([self.deviceModel.deviceTypeCode is233DeviceType]) {
        RHDataMonitor233VC *monitorVC = [[RHDataMonitor233VC alloc]init];
        monitorVC.curDevModel = self.deviceModel;
        monitorVC.endPointTypeModel = typeModel;
        monitorVC.updateDevStatus = ^{
            [weakSelf getDeviceStatus];
            [weakSelf getModueStatus];
        };
        return monitorVC;
    }
    
    //61度电
    if ([self.deviceModel.deviceTypeCode is61DeviceType]) {
        RHDataMonitorMe61VC *monitorVC = [[RHDataMonitorMe61VC alloc]init];
        monitorVC.curDevModel = self.deviceModel;
        monitorVC.endPointTypeModel = typeModel;
        monitorVC.updateDevStatus = ^{
            [weakSelf getDeviceStatus];
            [weakSelf getModueStatus];
        };
        return monitorVC;
    }
    
    //215k
    if ([self.deviceModel.deviceTypeCode isEqualToString:R_EC215100D0]) {
        RHDataMonitorMe215VC *monitorVC = [[RHDataMonitorMe215VC alloc]init];
        monitorVC.curDevModel = self.deviceModel;
        monitorVC.endPointTypeModel = typeModel;
        monitorVC.updateDevStatus = ^{
            [weakSelf getDeviceStatus];
            [weakSelf getModueStatus];
        };
        return monitorVC;
    }
    //1.67M
    if ([self.deviceModel.deviceTypeCode isEqualToString:R_SM1672LCBO1_EU]) {
        RHDataMonitorMe167MVC *monitorVC = [[RHDataMonitorMe167MVC alloc]init];
        monitorVC.curDevModel = self.deviceModel;
        monitorVC.endPointTypeModel = typeModel;
        monitorVC.updateDevStatus = ^{
            [weakSelf getDeviceStatus];
            [weakSelf getModueStatus];
        };
        return monitorVC;
    }
    
    //户用 , 一体机
    RHDeviceInverterDataVC *inverterVC = [[RHDeviceInverterDataVC alloc]init];
    inverterVC.curDevModel = self.deviceModel;
    inverterVC.endPointTypeModel = typeModel;
    inverterVC.updateDevStatus = ^{
        [weakSelf getDeviceStatus];
        [weakSelf getModueStatus];
    };
    return inverterVC;

 
}

-(LYEmptyView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
        _emptyView.frame = CGRectMake((kUI_WINDOW_W-100)/2, (kUI_WINDOW_H-100-kNavHeight)/2, 100, 100);
       
    }
    return _emptyView;
}


@end
